package com.example.shopsystem.control;

import com.example.shopsystem.aop.TokenMethod;
import com.example.shopsystem.entity.Administrator;
import com.example.shopsystem.entity.Business;
import com.example.shopsystem.service.AdminServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/admin")
public class AdminRg {
    @Autowired
    AdminServiceImpl adminService;

    @PostMapping("/adminRegister")
    public Result<Object> adminRegister(@RequestBody Administrator administrator) {//注册
        if (administrator.getPhone().length() <= 6 || administrator.getPwd().length() <= 6) {
            return Result.formatError(null);
        }
        if (String.valueOf(administrator.getType()) == null) {
            return Result.fieldMiss(null);
        }
        if (!adminService.adminRegister(administrator)) {
            return Result.formatError(null);
        }
        return Result.ok(null);
    }

    @PostMapping("/admLogin")
    public Result<Object> admLogin(@RequestBody Administrator administrator, HttpServletResponse response) {
        if (administrator.getPwd().length() <= 6) {
            return Result.formatError(null);
        }
        if (!adminService.admLogin(administrator)) {
            return Result.pwdBad(null);
        }
        String type = "admin";
        long exTime = System.currentTimeMillis() + 10000 * 60;
        String org = administrator.getId() + ";" + administrator.getPwd() + ";" + exTime + ";" + type;
        //生成token
        String token = TokenMethod.token(org);
        //把token放到头部
        response.setHeader("Token", token);
        return Result.ok(null);
    }
}